import { app, BrowserWindow, ipcMain, Menu } from 'electron';
import { join } from 'path';
import Store from 'electron-store';

interface StoreSchema {
  windowBounds: {
    width: number;
    height: number;
    x?: number;
    y?: number;
  };
  searchHistory: string[];
}

const store = new Store<StoreSchema>({
  defaults: {
    windowBounds: { width: 1200, height: 800 },
    searchHistory: [],
  },
});

let mainWindow: BrowserWindow | null = null;

function createWindow() {
  const bounds = store.get('windowBounds');
  
  mainWindow = new BrowserWindow({
    width: bounds.width,
    height: bounds.height,
    x: bounds.x,
    y: bounds.y,
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../shared/preload.js'),
    },
    titleBarStyle: 'hiddenInset',
    frame: false,
    show: false,
  });

  const isDev = process.env.NODE_ENV === 'development';
  
  if (isDev) {
    mainWindow.loadURL('http://localhost:3000');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow?.show();
  });

  mainWindow.on('close', () => {
    if (mainWindow) {
      store.set('windowBounds', mainWindow.getBounds());
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // 创建菜单
  createMenu();
}

function createMenu() {
  const template = [
    {
      label: 'CleanFinder',
      submenu: [
        { label: '关于 CleanFinder', role: 'about' },
        { type: 'separator' },
        { label: '隐藏 CleanFinder', accelerator: 'CmdOrCtrl+H', role: 'hide' },
        { label: '隐藏其他', role: 'hideothers' },
        { label: '显示全部', role: 'unhide' },
        { type: 'separator' },
        { label: '退出', accelerator: 'CmdOrCtrl+Q', role: 'quit' }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectall' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'Shift+CmdOrCtrl+R', role: 'forcereload' },
        { label: '切换开发者工具', accelerator: 'F12', role: 'toggledevtools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetzoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomin' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomout' },
        { type: 'separator' },
        { label: '切换全屏', accelerator: 'F11', role: 'togglefullscreen' }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// IPC 处理
ipcMain.handle('search-software', async (event, keyword: string) => {
  try {
    // 这里将集成 AI 搜索逻辑
    const results = await searchSoftware(keyword);
    
    // 保存搜索历史
    const history = store.get('searchHistory');
    if (!history.includes(keyword)) {
      store.set('searchHistory', [...history, keyword]);
    }
    
    return results;
  } catch (error) {
    console.error('搜索失败:', error);
    throw error;
  }
});

ipcMain.handle('get-search-history', () => {
  return store.get('searchHistory');
});

async function searchSoftware(keyword: string) {
  // 模拟 AI 搜索结果
  // 实际实现中将调用后端 API
  const mockResults = [
    {
      name: 'Shotcut',
      description: '免费开源的视频编辑软件',
      website: 'https://shotcut.org',
      icon: '🎬',
      tags: ['视频编辑', '开源', '跨平台']
    },
    {
      name: 'DaVinci Resolve',
      description: '专业级视频编辑和调色软件',
      website: 'https://www.blackmagicdesign.com/products/davinciresolve',
      icon: '🎨',
      tags: ['视频编辑', '专业', '调色']
    },
    {
      name: 'OpenShot',
      description: '简单易用的开源视频编辑器',
      website: 'https://www.openshot.org',
      icon: '🎞️',
      tags: ['视频编辑', '开源', '简单']
    }
  ];

  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  return mockResults.filter(item => 
    item.name.toLowerCase().includes(keyword.toLowerCase()) ||
    item.description.toLowerCase().includes(keyword.toLowerCase()) ||
    item.tags.some(tag => tag.toLowerCase().includes(keyword.toLowerCase()))
  );
}

// 应用事件
app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
